<script setup>
import { reactive, ref } from 'vue'
import { post } from '@/util/axios.js'
import { ElMessage } from 'element-plus';
import router from '../../router';

const active = ref(0)
const form = reactive({
  email: '',
  code:'',
  password: '',
  passwordRepeat: ''
})

const isEmailValid = ref(false)
const onValidate = (prop, isValid) => {
  if (prop === 'email') 
    isEmailValid.value = isValid
}

const validatePassword = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入密码'))
  } else if (value !== form.password) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}

const rules = {
  email: [
    { required: true, message: '请输入电子邮件地址', trigger: 'blur'},
    { type: 'email', message:'请输入合法的电子邮件地址', trigger: ['blur', 'change']}
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur'}
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur'},
    { min:6, max: 18, message: '密码的长度必须是6-18个字符', trigger: 'blur'}
  ],
  passwordRepeat: [
    { validator: validatePassword, trigger: 'blur'}
  ],
}

const coldTime = ref(0)
const validateEmail = () => {
  coldTime.value = 60
 
  post('/api/auth/valid-reset-email', {
    email: form.email
  }, (message) => {
    ElMessage.success(message)
    setInterval(() => { coldTime.value-- }, 1000)
  }, (message) => { 
    ElMessage.warning(message)
    coldTime.value = 0 
  })
}

const formRef = ref()
const startReset = () => {
  formRef.value.validate((isValid) => {
    if (isValid) {
      post('/api/auth/start-reset', {
        email: form.email,
        code: form.code
      }, () => {
        active.value++
      })
      } else {
        ElMessage.warning("请填写电子邮件地址和验证码")
      }
  })
}

const doReset = () => {
  formRef.value.validate((isValid) => {
    if (isValid) {
      post('/api/auth/do-reset', {
        password: form.password
      }, (message) => { 
        ElMessage.success(message)
        router.push('/')
      })
    }
  })
}
</script>

<template>
  <div style="margin: 100px 20px; font-size: 16px">
    <el-steps :active="active" finish-status="success" align-center >
      <el-step title="Verify Email"></el-step>
      <el-step title="Reset Password"></el-step>
    </el-steps>
  </div>

  <div style="text-align: center; margin: 0 20px;" v-if="active === 0">
    <div class="bs-title" style="margin-top: 80px;">
      <div style="font-size: 25px; font-weight: 600;">Verify Email</div>
    </div>

    <div style="margin-top: 30px;">
      <el-form :model="form" :rules="rules" @validate="onValidate" ref="formRef">
        <el-form-item prop="email">
          <el-input v-model="form.email" type="email" placeholder="bind your email" >
            <template #prefix>
              <el-icon><Message/></el-icon>
            </template>  
          </el-input> 
        </el-form-item>

        <el-form-item prop="code">
          <div style="display: flex; justify-content:space-between; width: 100%;">
            <el-input v-model="form.code" type="text" placeholder="received code"  :maxlength="6">
                <template #prefix>
                  <el-icon><EditPen/></el-icon> 
                </template>  
              </el-input>

              <el-button @click="validateEmail" class="btn" :class="{codeBtn: isEmailValid}"  
                        style="--bg: #b675b8; --cl: #fff; margin-left: 10px;" :disabled="!isEmailValid || coldTime > 0">
                {{coldTime > 0 ? `wait for ${coldTime}s` : "Send Code"}}
              </el-button>
          </div>
        </el-form-item>
      </el-form>
    </div>

    <div>
      <el-button @click="startReset">Reset Now</el-button>
    </div>
  </div>

  
  <div style="text-align: center; margin: 0 20px;" v-if="active === 1">
    <div class="bs-title" style="margin-top: 80px;">
      <div style="font-size: 25px; font-weight: 600;">Reset Password</div>
    </div>

    <div>
      <div style="margin-top: 30px;">
        <el-form :model="form" :rules="rules" ref="formRef">
          <el-form-item prop="password">
            <el-input v-model="form.password" :maxlength="18" type="password" placeholder="password" >
              <template #prefix>
                <el-icon><Lock/></el-icon>
              </template>  
            </el-input>
          </el-form-item>

          <el-form-item prop="passwordRepeat">
            <el-input v-model="form.passwordRepeat" :maxlength="18" type="password" placeholder="duplicate password" >
              <template #prefix>
                <el-icon><Lock/></el-icon>
              </template>  
            </el-input> 
          </el-form-item>
        </el-form>
      </div>

      <div>
        <el-button @click="doReset">Reset Now</el-button>
      </div>
    </div>
  </div>
</template>

<style>

</style>